package com.partsoft.dits.transform;


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.util.ObjectUtils;

public class ContextTransformReactor extends BaseTransformReactor implements InitializingBean, ApplicationListener<ApplicationContextEvent>, ApplicationContextAware {
	
	private ApplicationContext ownerContext;
	
	protected ApplicationContext getOwnerContext() {
		return ownerContext;
	}

	public void afterPropertiesSet() throws Exception {
		initContext();
	}

	public void onApplicationEvent(ApplicationContextEvent event) {
		if (!ObjectUtils.nullSafeEquals(getOwnerContext(), event.getApplicationContext())) return;
		if (event instanceof ContextRefreshedEvent) {
			initContext();
		} else if (event instanceof ContextClosedEvent) {
			finiContext();
		}
	}

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		ownerContext = applicationContext;
	}
	
}
